package gamble.notice.command;

import gamble.notice.dao.BoardDaoImp;
import gamble.notice.vo.BoardVO;

import java.io.File;

import java.io.FileOutputStream;

import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;

import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;


@Controller
//@RequestMapping("/write.htm")
public class WriteController  {
	
	private BoardDaoImp dao;
	private String realUploadPath;
	
	public void setDao(BoardDaoImp dao) {
		this.dao = dao;
	}	
	

	public void setRealUploadPath(String realUploadPath) {
		System.out.println("realUploadPath"+realUploadPath);
		this.realUploadPath = realUploadPath;
	}
	
	@RequestMapping(value="/write.htm",method=RequestMethod.GET)
    public String writeForm(){
    	return "writeForm";
    }

	
	
	@RequestMapping(value="/write.htm",method=RequestMethod.POST)
	public String writeSubmit(HttpServletRequest req,BoardVO vo){
	   
		 MultipartFile file=vo.getUpload();
		 //첨부파일이 존재하면
		 if(file!=null){
		 String fileName=file.getOriginalFilename();
		//System.out.println(new URLEncoder().encode(fileName));
		 
		// UUID random=UUID.randomUUID();
		// File ff=new File(realUploadPath,random+"_"+fileName);
		 File ff=new File(realUploadPath,fileName);
		 try{
		     FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(ff));
		 }catch(Exception ex){ex.getMessage();}
		
		 vo.setUpload2(""+ff);
		 }
		 
		 vo.setIp(req.getRemoteAddr());
		 if(vo.getRef() !=0){  //답변글.
			 vo.setRe_level(vo.getRe_level()+1);
			 vo.setRe_step(vo.getRe_step()+1);

		 }
		
		 dao.getInsert(vo);	
		return "redirect:/list.htm";
	}

}
